$(function(){
	var settingsEditForm = $('#settings-edit-form'),
		menu = {
			'重置': function(){
				settingsEditForm.find(':reset').click();
				var target = $('#site-logo-preview');
				$('input+i.glyphicon').hide();
				$.showMenu(null);
				if(target.length){
					var src = target.children('img').data('origin');
					target.children('img').attr('src', src);
					if(!src){
						target.hide();
					}
				}
			},
			'提交修改': function(){
				if(confirm('更改设置将会对你的网站外观和功能产生影响，确认？')){
					settingsEditForm.find(':submit').click();
				}
			}
		},
		target = _$('#settings').next('.badge');
	if(target.length){
		$('#list-group-item-update').append(target.prop('outerHTML'));
	}
	settingsEditForm.ajaxSubmit({
		beforeSend: function(){
			var img = $('#site-logo-preview>img');
			if(img.length && img.attr('src') != img.data('origin') && !img.data('uploaded')){
				$.upload({
					url: SITE_URL+'mod.php?file::upload',
					data: {file_desc: '用于网站 LOGO 的图片。'},
					success: function(result){
						if(result.success){
							settingsEditForm.find('input[name="site.logo"]').val(result.data[0].file_src);
							img.data('uploaded', true);
							settingsEditForm.submit();
						}else{
							if(typeof result.data == 'string'){
								alert(result.data);
							}else{
								alert(result.data[0].error);
							}
						}
					},
					error: function(xhr){
						alert('与服务器的连接出现错误，文件上传失败。');
						console.log(xhr.responseText);
					}
				});
				return false;
			}
		},
		success: function(result){
			if(result.success){
				alert('更新成功。');
				location.reload();
			}else{
				alert(result.data);
			}
		},
		error: function(xhr){
			console.log(xhr);
			alert('与服务器的连接出现错误，设置更新失败。');
		}
	}).find('select, :checkbox, :radio').change(function(){
		$.showMenu(menu);
	});
	settingsEditForm.find('input, textarea').on('input', function(){
		$.showMenu(menu);
	});

	/** 检查 CMS/ModPHP 更新 */
	$('#check-update, #check-modphp-update').click(function(){
		var $this = $(this),
			id = $this.attr('id'),
			isCms = id == 'check-update',
			type = isCms ? 'modcms' : 'modphp',
			version = isCms ? CMS_VERSION : MOD_VERSION,
			versionURL = isCms ? VERSION_URLS['modcms'] : VERSION_URLS['modphp'],
			newVersion = isCms ? $('#new-version') : $('#new-modphp-version'),
			updateVersion = isCms ? $('#update-new-version') : $('#update-new-modphp-version');
		$this.button('loading');
		$.ajax({
			url: SITE_URL+'mod.php?obj=mod&act=checkUpdate&type='+type+'&version='+version+'&versionURL='+versionURL,
			success: function(result){
				$this.hide().button('reset');
				if(version_compare(result.data.version, result.version) > 0){
					newVersion.html('有新版本可用：<code>'+result.data.version+'</code>。<a href="'+result.data.url+'" target="_blank">新版说明</a>').show();
					updateVersion.data('version', result.data).show();
				}else{
					newVersion.html('暂无可用更新。').show();
				}
			},
			error: function(){
				$this.hide().button('reset');
				newVersion.html('暂无可用更新。').show();
			}
		});
	});

	/** 更新 CMS/ModPHP/数据库 */
	$('#update-new-version, #update-new-modphp-version, #update-db').not('.disabled').click(function(){
		if(!confirm('即将永久修改网站功能，确认？')) return false;
		var $this = $(this),
			id = $this.attr('id'),
			isCms = id == 'update-new-version',
			version = $this.data('version'),
			method = isCms ? 'updateCMS' : 'update',
			storageKey = isCms ? 'newCMSVersion' : 'newMODVersion',
			upgrade = id == 'update-new-modphp-version';
		if(upgrade){
			version['upgrade'] = true;
		}
		$this.button('loading');
		$.ajax({
			url: SITE_URL+'mod.php?mod::'+method,
			type: 'post',
			data: version,
			success: function(result){
				alert(result.data);
				$this.button('reset');
				if(result.success){
					$.showNews('settings', '-1');
					if(upgrade || storageKey == 'newCMSVersion'){
						storage(storageKey, null);
					}
					$('#clear-temp').click();
				}
			},
			error: function(xhr){
				console.log(xhr);
				alert('与服务器的连接出现错误，系统更新失败。');
			}
		});
	});

	/** 清除缓存 */
	$('#clear-temp').click(function(){
		$.ajax({
			url: SITE_URL+'mod.php?file::removeTempFolder|folder:admin/template/', 
			success: function(result){
				alert(result.data);
				_window.location.reload();
			},
			error: function(xhr){
				console.log(xhr);
				alert('与服务器的连接出现错误，缓存清除失败。');
			}
		});
	});

	/** 上传网站 LOGO */
	$('#upload-logo').click(function(){
		var $this = $(this);
		$this.button('loading');
		$.upload({
			preview: '#site-logo-preview>img',
			success: function(img){
				settingsEditForm.find('input[name="site.logo"]').val(img[0]);
				$('#site-logo-preview').show();
				$.showMenu(menu);
				$this.button('reset').text('更换');
			}
		});
	});

	/** 检测数据库更新 */
	$.ajax({
		url: SITE_URL+'mod.php?mod::checkDbUpdate', 
		success: function(result){
			$('#new-db').text(result.data);
			if(result.success){
				$('#update-db').show();
			}
		},
		error: function(){
			$('#new-db').text('与服务器的连接出现错误，检测失败。');
		}
	});

	/** 检测CMS/ModPHP 更新 */
	if(storage('newCMSVersion')){
		$('#check-update').click();
	}
	if(storage('newMODVersion')){
		$('#check-modphp-update').click();
	}
});